package com.nord.Login;

import java.io.File;

import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.nord.R;
import com.nord.Menus.Menus;
import com.nord.Services.SQLiteAdapter;
import com.nord.WebTools.HtmlBrowser;

public class Welcome extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);
	}

	@Override
	public void onResume() {
		super.onResume();
		setContentView(R.layout.activity_welcome);
		HtmlBrowser.initializeHashMap();
		HtmlBrowser.initBrowser();

		Button menuBanner;
		Typeface tf;
		menuBanner = (Button) findViewById(R.id.menuBanner);
		tf = Typeface.createFromAsset(getAssets(), "DaysOne-Regular.ttf");
		if (tf != null && menuBanner != null) {
			menuBanner.setTypeface(tf);
		}
		File database = getApplicationContext().getDatabasePath("DATABASE");
		if (database.exists()) {
			new LoadCookie().execute();
		} else {
			// custom dialog
			final Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.dialog_welcome);

			Window window = dialog.getWindow();
			window.setLayout((int) (window.getWindowManager()
					.getDefaultDisplay().getWidth() * .90), (int) (window
					.getWindowManager().getDefaultDisplay().getHeight() * .90));

			dialog.setCancelable(false);

			dialog.setTitle("Velkomin/n");

			TextView texti = (TextView) dialog.findViewById(R.id.text1);

			texti.setText("Við viljum byrja á að óska þér til "
					+ "hamingju með að vera meðlimur í bezta og flottasta "
					+ "nemendafélagi sem sögur fara af.\n\n"
					+ "Þetta app gerir þér kleift að njóta góðs af þeim "
					+ "þjónustum sem www.nord.is hefur upp á að bjóða "
					+ "eins og að lesa fréttir, skrá þig í vísindaferðir,\n"
					+ "o.s.frv.");

			Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);

			dialogButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					startActivity(new Intent(Welcome.this, Login.class));
				}
			});
			dialog.show();
		}
	}

	/*
	 * Usage: new LoadCookie().execute(void); Pre : A database file exists Post
	 * : Cookie from a previous version has been loaded into the HtmlBrowser
	 */
	private class LoadCookie extends AsyncTask<Void, Integer, String> {
		ProgressDialog progressBar;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(Welcome.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að skrá þig á www.nord.is ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();
		}

		@Override
		protected String doInBackground(Void... args) {
			BasicCookieStore cookieStore = new BasicCookieStore();
			cookieStore.addCookies(HtmlBrowser.loadCookies(Welcome.this));
			((AbstractHttpClient) HtmlBrowser.httpBrowser)
					.setCookieStore(cookieStore);

			String[] htmlInfo = HtmlBrowser.getExecutor("https://www.nord.is/");
			
			if (!htmlInfo[0].contains("Exception")){
				if (!HtmlBrowser.cookieValidation(htmlInfo[1],Welcome.this)) 
					return "CookieException";
			}
			String username = "";
			SQLiteAdapter sql = new SQLiteAdapter(Welcome.this);
			sql.open("R");
			String[] columns = {"username","fullname"};
			Cursor cursor = sql.queryTable("user",columns);
			if (cursor.moveToFirst()) {
				username = cursor.getString(cursor.getColumnIndex("fullname"));
			}

			cursor.close();
			sql.close();
			return username;
		
		}

		@Override
		protected void onPostExecute(String username) {
			progressBar.dismiss();
			Intent nordMenu = new Intent(Welcome.this, Menus.class);
			if (!username.contains("CookieException")) {
				nordMenu.putExtra("USERNAME", username);
				startActivity(nordMenu);

			} else {
				HtmlBrowser.expiredCookieHandler(Welcome.this);
			}

		}
	}

}
